package zencstudio.sgrealtor.view.phone;

import zencstudio.sgrealtor.R;
import zencstudio.sgrealtor.model.PropertyDetail;
import zencstudio.sgrealtor.utils.Const;
import zencstudio.sgrealtor.utils.WFUtils;
import zencstudio.sgrealtor.view.common.NetWorkErrorActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.CancelableCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class PropertyMap extends FragmentActivity
	implements
	ConnectionCallbacks,
	OnConnectionFailedListener
	{

	private PropertyDetail property;
	private GoogleMap mMap;
	private LocationClient mLocationClient;
	 // These settings are the same as the settings for the map. They will in fact give you updates	
	 
    private void createMapIfReady() {
	        // Do a null check to confirm that we have not already instantiated the map.
	        if (mMap == null) {
	            // Try to obtain the map from the SupportMapFragment.
	            SupportMapFragment mapFragment =
	                    (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
	            mMap = mapFragment.getMap();
	            if (mMap != null) {
	                mMap.setMyLocationEnabled(false);	           
	            }
	        }
	    }
    private void setUpLocationClientIfNeeded() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(
                    getApplicationContext(),
                    this,  // ConnectionCallbacks
                    this); // OnConnectionFailedListener
        }
    }
	 @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        if(!WFUtils.checkInternetConnection(this)){
	        	Intent intent = new Intent(this,NetWorkErrorActivity.class);
	    		intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
	    		startActivityForResult(intent, Const.NETWORK_ACTIVITY_REQUEST_CODE);
	    		finish();
    			return;
    		}
	        setContentView(R.layout.property_map);
	        if(!WFUtils.checkLocationService(this))
	        	showLocationSettingDlg(R.string.msg_location_not_enabled);
	        property = (PropertyDetail) getIntent().getSerializableExtra(Const.PROPERTYID);

	        createMapIfReady();
	        setUpLocationClientIfNeeded();
	        mLocationClient.connect();
	    }
	 @Override
	    public void onPause() {
	        super.onPause();
	        if (mLocationClient != null) {
	            mLocationClient.disconnect();
	        }
	    }
	    @Override
	    protected void onResume() {
	        super.onResume();
        
            int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
            
            if (resultCode == ConnectionResult.SUCCESS){
            /* Toast.makeText(getApplicationContext(), 
               "isGooglePlayServicesAvailable SUCCESS", 
               Toast.LENGTH_LONG).show();*/
            }else{
             GooglePlayServicesUtil.getErrorDialog(resultCode, this, Const.RQS_GooglePlayServices).show();
            }
    	       
	    }
		@Override
		public void onConnectionFailed(ConnectionResult result) {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void onConnected(Bundle connectionHint) {		
			LatLng latlng = new LatLng(property.getLatitude(), property.getLongitude());
			changeCamera(latlng);
		}
		@Override
		public void onDisconnected() {
			// TODO Auto-generated method stub
			
		}
		/**
	     * Change the camera position by moving or animating the camera depending on the state of the
	     * animate toggle button.
	     */
	    private void changeCamera(final LatLng currLng) {
	    	CameraPosition currPos =
                    new CameraPosition.Builder().target(currLng)
                            .zoom(15.5f)
                            .bearing(0)
                            .tilt(25)
                            .build();
	    	mMap.animateCamera(CameraUpdateFactory.newCameraPosition(currPos), new CancelableCallback() {
	             @Override
	             public void onFinish() {
	            	 MarkerOptions mk = new MarkerOptions();
					 mk.position(currLng);
					 mk.draggable(false);
					 mk.title(property.getName());
		            mk.snippet(property.getLocation());
		            mMap.addMarker(mk).showInfoWindow();
	             }

	             @Override
	             public void onCancel() {
	                // Toast.makeText(getBaseContext(), "Animation to Sydney canceled", Toast.LENGTH_SHORT).show();
	             }
	         });
	        
	    }
	    protected void showLocationSettingDlg(int resString){
		
				AlertDialog.Builder dialog = new AlertDialog.Builder(this);
	            dialog.setMessage(getResources().getString(resString));
	            dialog.setPositiveButton(getResources().getString(R.string.msg_open_location_setting), new DialogInterface.OnClickListener() {

	                @Override
	                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
	                    // TODO Auto-generated method stub
	                    Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS );
	                    startActivity(myIntent);
	                    finish();
	                }
	            });          
	            dialog.show();
			
		}	   
}
